package com.tanguy.driver.ui.window

import android.support.v7.app.AppCompatActivity
import android.view.View
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.MapView

import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import com.tanguy.driver.R
import com.tanguy.driver.base.BasePopupWindow
import com.tanguy.driver.bean.socket.NewOrder
import com.tanguy.driver.ui.map.overlay.DrivingRouteOverlay
import com.tanguy.driver.utlis.TimeUtils
import com.tanguy.driver.utlis.extend.countDownTimer
import com.tanguy.driver.utlis.extend.loge
import com.tanguy.driver.utlis.extend.toTimeString
import com.tanguy.user.custom.SpanBuilder
import com.tanguy.user.utlis.extend.click
import com.tanguy.user.utlis.extend.setText
import io.reactivex.disposables.Disposable
import org.jetbrains.anko.find
import java.util.*

/**
 * Created by dab on 2017/11/28 0028 11:45
 *  新订单来了
 */
class NewOrderWindow(val activity: AppCompatActivity, val newOrder: NewOrder, val grabOrder: (newOrder: NewOrder) -> Unit) : BasePopupWindow(activity) {
    override fun setContentRes(): Int = R.layout.window_new_order
    val routeSearch by lazy { RouteSearch(activity) }
    lateinit var mapView: MapView
    var mCountDownTimer: Disposable? = null
    //    val fragment by lazy { activity.supportFragmentManager.findFragmentById(R.id.map)as SupportMapFragment }
    override fun initView(view: View) {
        super.initView(view)
        loge(newOrder.toString())
        view.apply {
            mapView = find(R.id.map)
            initMapView(mapView.map)
            mapView.onCreate(null)
            mapView.onResume()
            click(R.id.iv_close) { dismiss() }
            click(R.id.tv_next) {
                grabOrder.invoke(newOrder)
                dismiss()
            }
            val content = "距您 ${newOrder.km} 公里"
            val build = SpanBuilder(content).size(3, content.length - 3, 29).build()
            setText(R.id.tv_km, build)
            setText(R.id.tv_type, newOrder.typeString + "订单")
            setText(R.id.tv_time, getTimeDDMM(newOrder.bybustime))
            setText(R.id.tv_start, newOrder.departure)
            setText(R.id.tv_end, newOrder.bourn)
            setText(R.id.tv_totalkm, "全程${newOrder.totalkm}公里")
        }
        mCountDownTimer = countDownTimer(30) { finish, millisUntilFinished ->
            if (finish) {
                dismiss()
            } else {
                view.setText(R.id.tv_next, "抢单\n${millisUntilFinished}s")
            }
        }
    }


    private fun initMapView(map: AMap) {
        // 通用设置
        val uiSettings = map.uiSettings
        uiSettings.isZoomControlsEnabled = false
        uiSettings.isZoomGesturesEnabled = false
        uiSettings.isScrollGesturesEnabled = false
        uiSettings.logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT//设置logo位置
        val fromAndTo = RouteSearch.FromAndTo(LatLonPoint(newOrder.deplat, newOrder.deplon), LatLonPoint(newOrder.boulat, newOrder.boulon))
        val query = RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "")
        routeSearch.calculateDriveRouteAsyn(query)

        routeSearch.setRouteSearchListener(object : RouteSearch.OnRouteSearchListener {
            override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {}
            override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {}
            override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {}
            override fun onDriveRouteSearched(p0: DriveRouteResult?, p1: Int) {
                if (p1 != 1000) return
                if (p0 == null || p0.paths == null || p0.paths.size <= 0) return
                val drivePath = p0.paths[0]
                val drivingRouteOverlay = DrivingRouteOverlay(activity, map, drivePath, p0.startPos, p0.targetPos)
                drivingRouteOverlay.removeFromMap()
                drivingRouteOverlay.setNodeIconVisibility(false)
                drivingRouteOverlay.addToMap()
                drivingRouteOverlay.zoomToSpan()
            }


        })

    }


    override fun dismiss() {
        super.dismiss()
        mapView.onPause()
        mapView.onDestroy()
        mCountDownTimer?.dispose()
    }


    fun getTimeDDMM(time: Long, nowTime: Long = System.currentTimeMillis()): String {
        fun getStartTimeOfDay(now: Long): Long {
            val tz = "GMT+8"
            val curTimeZone = TimeZone.getTimeZone(tz)
            val calendar = Calendar.getInstance(curTimeZone)
            calendar.timeInMillis = now
            calendar.set(Calendar.HOUR_OF_DAY, 0)
            calendar.set(Calendar.MINUTE, 0)
            calendar.set(Calendar.SECOND, 0)
            calendar.set(Calendar.MILLISECOND, 0)
            return calendar.timeInMillis
        }

        var desc = ""
        val startTimeOfDay = getStartTimeOfDay(nowTime)
        val l = time - startTimeOfDay
        val data = l / 1000 / 24 / 60 / 60
        when (data.toInt()) {
            -1 -> desc = "前天"
            0 -> desc = if (l > 0) "今天" else "昨天"
            1 -> desc = "明天"
            2 -> desc = "后天"
        }

        return desc + time.toTimeString(TimeUtils.HH_MM)
    }
}